<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Messaging WebSocket Test</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            max-width: 1200px;
            margin: 0 auto;
        }
        .container {
            display: flex;
            gap: 20px;
        }
        .panel {
            flex: 1;
            border: 1px solid #ccc;
            border-radius: 5px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .message-container {
            height: 300px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 10px;
            margin-bottom: 10px;
            background-color: #f9f9f9;
        }
        .message {
            margin-bottom: 8px;
            padding: 8px;
            border-radius: 5px;
        }
        .received {
            background-color: #e3f2fd;
            border-left: 4px solid #2196F3;
        }
        .sent {
            background-color: #e8f5e9;
            border-left: 4px solid #4CAF50;
        }
        .system {
            background-color: #fff3e0;
            border-left: 4px solid #FF9800;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input, textarea, select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 5px;
        }
        button:hover {
            background-color: #45a049;
        }
        button.secondary {
            background-color: #2196F3;
        }
        button.secondary:hover {
            background-color: #0b7dda;
        }
        button.danger {
            background-color: #f44336;
        }
        button.danger:hover {
            background-color: #d32f2f;
        }
        .status {
            padding: 5px 10px;
            border-radius: 4px;
            display: inline-block;
            margin-bottom: 10px;
        }
        .online {
            background-color: #c8e6c9;
            color: #2e7d32;
        }
        .offline {
            background-color: #ffcdd2;
            color: #c62828;
        }
        .user-list {
            margin-top: 10px;
        }
        .user-item {
            padding: 5px;
            margin-bottom: 5px;
            border-radius: 4px;
            cursor: pointer;
        }
        .user-item:hover {
            background-color: #f5f5f5;
        }
        .user-item.selected {
            background-color: #e3f2fd;
            border-left: 4px solid #2196F3;
        }
        .tabs {
            display: flex;
            margin-bottom: 10px;
        }
        .tab {
            padding: 10px 15px;
            cursor: pointer;
            background-color: #f1f1f1;
            border: 1px solid #ccc;
            border-bottom: none;
            border-radius: 5px 5px 0 0;
            margin-right: 5px;
        }
        .tab.active {
            background-color: white;
            border-bottom: 1px solid white;
        }
        .tab-content {
            display: none;
            border: 1px solid #ccc;
            padding: 15px;
            border-radius: 0 5px 5px 5px;
        }
        .tab-content.active {
            display: block;
        }
    </style>
</head>
<body>
    <h1>Messaging WebSocket Test</h1>
    
    <div class="panel">
        <h2>Connection</h2>
        <div class="form-group">
            <label for="username">Username:</label>
            <input type="text" id="username" placeholder="Enter your username">
        </div>
        <div class="form-group">
            <label for="serverUrl">Server URL:</label>
            <input type="text" id="serverUrl" value="/MessagingWebSocketServer">
        </div>
        <div>
            <button id="connectBtn">Connect</button>
            <button id="disconnectBtn" class="danger" disabled>Disconnect</button>
            <span id="connectionStatus" class="status offline">Disconnected</span>
        </div>
    </div>

    <div class="container">
        <div class="panel">
            <h2>Users</h2>
            <div id="userList" class="user-list">
                <p>No users online</p>
            </div>
        </div>
        
        <div class="panel">
            <h2>Messages</h2>
            <div id="messageContainer" class="message-container"></div>
            
            <div class="tabs">
                <div class="tab active" data-tab="text">Text</div>
                <div class="tab" data-tab="file">File</div>
                <div class="tab" data-tab="friend">Friend</div>
                <div class="tab" data-tab="moment">Moment</div>
            </div>
            
            <div id="textTab" class="tab-content active">
                <div class="form-group">
                    <label for="recipient">To User:</label>
                    <input type="text" id="recipient" placeholder="Enter recipient username">
                </div>
                <div class="form-group">
                    <label for="messageText">Message:</label>
                    <textarea id="messageText" placeholder="Enter your message"></textarea>
                </div>
                <button id="sendTextBtn" disabled>Send Text Message</button>
                <button id="sendTypingBtn" disabled>Send Typing Notification</button>
            </div>
            
            <div id="fileTab" class="tab-content">
                <div class="form-group">
                    <label for="fileRecipient">To User:</label>
                    <input type="text" id="fileRecipient" placeholder="Enter recipient username">
                </div>
                <div class="form-group">
                    <label for="fileInput">Select File:</label>
                    <input type="file" id="fileInput">
                </div>
                <button id="sendFileBtn" disabled>Send File</button>
            </div>
            
            <div id="friendTab" class="tab-content">
                <div class="form-group">
                    <label for="friendUsername">Username:</label>
                    <input type="text" id="friendUsername" placeholder="Enter friend's username">
                </div>
                <div class="form-group">
                    <label for="friendMessage">Message:</label>
                    <textarea id="friendMessage" placeholder="Enter verification message"></textarea>
                </div>
                <button id="sendFriendRequestBtn" disabled>Send Friend Request</button>
                <button id="acceptFriendBtn" disabled>Accept Friend Request</button>
                <button id="rejectFriendBtn" disabled>Reject Friend Request</button>
            </div>
            
            <div id="momentTab" class="tab-content">
                <div class="form-group">
                    <label for="momentContent">Content:</label>
                    <textarea id="momentContent" placeholder="What's on your mind?"></textarea>
                </div>
                <div class="form-group">
                    <label for="momentMediaUrls">Media URLs (comma separated):</label>
                    <input type="text" id="momentMediaUrls" placeholder="http://example.com/image1.jpg, http://example.com/image2.jpg">
                </div>
                <button id="postMomentBtn" disabled>Post Moment</button>
                <hr>
                <div class="form-group">
                    <label for="momentId">Moment ID:</label>
                    <input type="text" id="momentId" placeholder="Enter moment ID">
                </div>
                <div class="form-group">
                    <label for="momentOwner">Moment Owner:</label>
                    <input type="text" id="momentOwner" placeholder="Enter moment owner's username">
                </div>
                <div class="form-group">
                    <label for="commentText">Comment:</label>
                    <textarea id="commentText" placeholder="Enter your comment"></textarea>
                </div>
                <button id="likeBtn" disabled>Like</button>
                <button id="commentBtn" disabled>Comment</button>
            </div>
        </div>
    </div>

    <script>
        let socket;
        let currentUser = '';
        let pendingFileTransfer = null;
        let userStatusMap = {};
        
        // DOM Elements
        const connectBtn = document.getElementById('connectBtn');
        const disconnectBtn = document.getElementById('disconnectBtn');
        const sendTextBtn = document.getElementById('sendTextBtn');
        const sendTypingBtn = document.getElementById('sendTypingBtn');
        const sendFileBtn = document.getElementById('sendFileBtn');
        const sendFriendRequestBtn = document.getElementById('sendFriendRequestBtn');
        const acceptFriendBtn = document.getElementById('acceptFriendBtn');
        const rejectFriendBtn = document.getElementById('rejectFriendBtn');
        const postMomentBtn = document.getElementById('postMomentBtn');
        const likeBtn = document.getElementById('likeBtn');
        const commentBtn = document.getElementById('commentBtn');
        const connectionStatus = document.getElementById('connectionStatus');
        const messageContainer = document.getElementById('messageContainer');
        const userList = document.getElementById('userList');
        
        // Tab handling
        const tabs = document.querySelectorAll('.tab');
        const tabContents = document.querySelectorAll('.tab-content');
        
        tabs.forEach(tab => {
            tab.addEventListener('click', () => {
                const tabId = tab.getAttribute('data-tab');
                
                tabs.forEach(t => t.classList.remove('active'));
                tabContents.forEach(content => content.classList.remove('active'));
                
                tab.classList.add('active');
                document.getElementById(`${tabId}Tab`).classList.add('active');
            });
        });
        
        // Connect to WebSocket
        connectBtn.addEventListener('click', () => {
            const username = document.getElementById('username').value.trim();
            const serverUrl = document.getElementById('serverUrl').value.trim();
            
            if (!username) {
                addSystemMessage('Please enter a username');
                return;
            }
            
            currentUser = username;
            
            // Get the protocol (ws or wss)
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const host = window.location.host;
            const wsUrl = `${protocol}//${host}${serverUrl}?username=${encodeURIComponent(username)}`;
            
            try {
                socket = new WebSocket(wsUrl);
                
                socket.onopen = () => {
                    setConnectionStatus(true);
                    addSystemMessage('Connected to server');
                };
                
                socket.onclose = () => {
                    setConnectionStatus(false);
                    addSystemMessage('Disconnected from server');
                };
                
                socket.onerror = (error) => {
                    console.error('WebSocket error:', error);
                    addSystemMessage('WebSocket error occurred');
                    setConnectionStatus(false);
                };
                
                socket.onmessage = (event) => {
                    handleMessage(event.data);
                };
            } catch (error) {
                console.error('Connection error:', error);
                addSystemMessage(`Connection error: ${error.message}`);
            }
        });
        
        // Disconnect from WebSocket
        disconnectBtn.addEventListener('click', () => {
            if (socket && socket.readyState === WebSocket.OPEN) {
                socket.close();
            }
        });
        
        // Send text message
        sendTextBtn.addEventListener('click', () => {
            const recipient = document.getElementById('recipient').value.trim();
            const messageText = document.getElementById('messageText').value.trim();
            
            if (!recipient || !messageText) {
                addSystemMessage('Please enter recipient and message');
                return;
            }
            
            const message = {
                type: 'TEXT',
                toUser: recipient,
                content: messageText
            };
            
            sendMessage(message);
            addMessage('sent', `To ${recipient}: ${messageText}`);
            document.getElementById('messageText').value = '';
        });
        
        // Send typing notification
        sendTypingBtn.addEventListener('click', () => {
            const recipient = document.getElementById('recipient').value.trim();
            
            if (!recipient) {
                addSystemMessage('Please enter recipient');
                return;
            }
            
            const message = {
                type: 'TYPING',
                toUser: recipient
            };
            
            sendMessage(message);
            addSystemMessage(`Sent typing notification to ${recipient}`);
        });
        
        // Send file
        sendFileBtn.addEventListener('click', () => {
            const recipient = document.getElementById('fileRecipient').value.trim();
            const fileInput = document.getElementById('fileInput');
            
            if (!recipient || !fileInput.files.length) {
                addSystemMessage('Please enter recipient and select a file');
                return;
            }
            
            const file = fileInput.files[0];
            
            // Send file transfer request
            const message = {
                type: 'FILE_TRANSFER_REQUEST',
                toUser: recipient,
                content: file.name,
                fileType: file.type,
                fileSize: file.size
            };
            
            pendingFileTransfer = {
                file: file,
                recipient: recipient
            };
            
            sendMessage(message);
            addSystemMessage(`Sending file transfer request for ${file.name} (${formatFileSize(file.size)})`);
        });
        
        // Send friend request
        sendFriendRequestBtn.addEventListener('click', () => {
            const friendUsername = document.getElementById('friendUsername').value.trim();
            const friendMessage = document.getElementById('friendMessage').value.trim();
            
            if (!friendUsername) {
                addSystemMessage('Please enter friend username');
                return;
            }
            
            const message = {
                type: 'FRIEND_REQUEST',
                toUser: friendUsername,
                content: friendMessage || 'I would like to add you as a friend'
            };
            
            sendMessage(message);
            addSystemMessage(`Sent friend request to ${friendUsername}`);
        });
        
        // Accept friend request
        acceptFriendBtn.addEventListener('click', () => {
            const friendUsername = document.getElementById('friendUsername').value.trim();
            
            if (!friendUsername) {
                addSystemMessage('Please enter friend username');
                return;
            }
            
            const message = {
                type: 'FRIEND_RESPONSE',
                toUser: friendUsername,
                content: 'accept'
            };
            
            sendMessage(message);
            addSystemMessage(`Accepted friend request from ${friendUsername}`);
        });
        
        // Reject friend request
        rejectFriendBtn.addEventListener('click', () => {
            const friendUsername = document.getElementById('friendUsername').value.trim();
            
            if (!friendUsername) {
                addSystemMessage('Please enter friend username');
                return;
            }
            
            const message = {
                type: 'FRIEND_RESPONSE',
                toUser: friendUsername,
                content: 'reject'
            };
            
            sendMessage(message);
            addSystemMessage(`Rejected friend request from ${friendUsername}`);
        });
        
        // Post moment
        postMomentBtn.addEventListener('click', () => {
            const momentContent = document.getElementById('momentContent').value.trim();
            const momentMediaUrls = document.getElementById('momentMediaUrls').value.trim();
            
            if (!momentContent) {
                addSystemMessage('Please enter moment content');
                return;
            }
            
            const message = {
                type: 'MOMENT',
                content: momentContent
            };
            
            if (momentMediaUrls) {
                message.mediaUrls = momentMediaUrls.split(',').map(url => url.trim());
            }
            
            sendMessage(message);
            addSystemMessage('Posted moment');
        });
        
        // Like moment
        likeBtn.addEventListener('click', () => {
            const momentId = document.getElementById('momentId').value.trim();
            const momentOwner = document.getElementById('momentOwner').value.trim();
            
            if (!momentId || !momentOwner) {
                addSystemMessage('Please enter moment ID and owner');
                return;
            }
            
            const message = {
                type: 'LIKE',
                toUser: momentOwner,
                momentId: momentId
            };
            
            sendMessage(message);
            addSystemMessage(`Liked moment ${momentId}`);
        });
        
        // Comment on moment
        commentBtn.addEventListener('click', () => {
            const momentId = document.getElementById('momentId').value.trim();
            const momentOwner = document.getElementById('momentOwner').value.trim();
            const commentText = document.getElementById('commentText').value.trim();
            
            if (!momentId || !momentOwner || !commentText) {
                addSystemMessage('Please enter moment ID, owner, and comment');
                return;
            }
            
            const message = {
                type: 'COMMENT',
                toUser: momentOwner,
                momentId: momentId,
                content: commentText
            };
            
            sendMessage(message);
            addSystemMessage(`Commented on moment ${momentId}`);
            document.getElementById('commentText').value = '';
        });
        
        // Handle incoming messages
        function handleMessage(data) {
            try {
                const message = JSON.parse(data);
                console.log('Received message:', message);
                
                switch (message.type) {
                    case 'SYSTEM':
                        handleSystemMessage(message);
                        break;
                    case 'TEXT':
                        handleTextMessage(message);
                        break;
                    case 'FILE_TRANSFER_REQUEST':
                        handleFileTransferRequest(message);
                        break;
                    case 'FILE_METADATA':
                        handleFileMetadata(message);
                        break;
                    case 'FRIEND_REQUEST':
                        handleFriendRequest(message);
                        break;
                    case 'FRIEND_RESPONSE':
                        handleFriendResponse(message);
                        break;
                    case 'MOMENT':
                        handleMoment(message);
                        break;
                    case 'LIKE':
                        handleLike(message);
                        break;
                    case 'COMMENT':
                        handleComment(message);
                        break;
                    case 'TYPING':
                        handleTyping(message);
                        break;
                    case 'USER_STATUS':
                        handleUserStatus(message);
                        break;
                    case 'DELIVERY_RECEIPT':
                        handleDeliveryReceipt(message);
                        break;
                    case 'READ_RECEIPT':
                        handleReadReceipt(message);
                        break;
                    default:
                        addSystemMessage(`Received unknown message type: ${message.type}`);
                }
            } catch (error) {
                console.error('Error parsing message:', error);
                addSystemMessage(`Error parsing message: ${error.message}`);
            }
        }
        
        // Handle system messages
        function handleSystemMessage(message) {
            addSystemMessage(message.content);
            
            if (message.status === 'READY_FOR_TRANSFER' && pendingFileTransfer) {
                sendFileData(message.fileId);
            }
        }
        
        // Handle text messages
        function handleTextMessage(message) {
            const from = message.fromUser;
            const content = message.content;
            
            addMessage('received', `From ${from}: ${content}`);
            
            // Send read receipt
            if (message.messageId) {
                sendReadReceipt(from, message.messageId);
            }
        }
        
        // Handle file transfer request
        function handleFileTransferRequest(message) {
            const from = message.fromUser;
            const fileName = message.content;
            const fileSize = message.fileSize;
            
            addMessage('received', `${from} wants to send you a file: ${fileName} (${formatFileSize(fileSize)})`);
        }
        
        // Handle file metadata
        function handleFileMetadata(message) {
            const from = message.fromUser;
            const fileName = message.content;
            
            addMessage('received', `Receiving file from ${from}: ${fileName}`);
        }
        
        // Handle friend request
        function handleFriendRequest(message) {
            const from = message.fromUser;
            const content = message.content;
            
            addMessage('received', `Friend request from ${from}: "${content}"`);
            document.getElementById('friendUsername').value = from;
        }
        
        // Handle friend response
        function handleFriendResponse(message) {
            const from = message.fromUser;
            const accepted = message.content === 'accept';
            
            addMessage('received', `${from} has ${accepted ? 'accepted' : 'rejected'} your friend request`);
        }
        
        // Handle moment
        function handleMoment(message) {
            const from = message.fromUser;
            const content = message.content;
            const momentId = message.momentId;
            const mediaUrls = message.mediaUrls || [];
            
            let momentText = `${from} posted: "${content}"`;
            if (mediaUrls.length > 0) {
                momentText += ` with ${mediaUrls.length} media items`;
            }
            momentText += ` (ID: ${momentId})`;
            
            addMessage('received', momentText);
            
            // Pre-fill moment fields for interaction
            document.getElementById('momentId').value = momentId;
            document.getElementById('momentOwner').value = from;
        }
        
        // Handle like
        function handleLike(message) {
            const from = message.fromUser;
            const momentId = message.momentId;
            
            addMessage('received', `${from} liked your moment (ID: ${momentId})`);
        }
        
        // Handle comment
        function handleComment(message) {
            const from = message.fromUser;
            const momentId = message.momentId;
            const content = message.content;
            
            addMessage('received', `${from} commented on your moment (ID: ${momentId}): "${content}"`);
        }
        
        // Handle typing notification
        function handleTyping(message) {
            const from = message.fromUser;
            
            addSystemMessage(`${from} is typing...`);
        }
        
        // Handle user status
        function handleUserStatus(message) {
            const username = message.fromUser;
            const status = message.content;
            
            userStatusMap[username] = status === 'online';
            updateUserList();
            
            addSystemMessage(`${username} is now ${status}`);
        }
        
        // Handle delivery receipt
        function handleDeliveryReceipt(message) {
            const messageId = message.messageId;
            
            addSystemMessage(`Message delivered (ID: ${messageId})`);
        }
        
        // Handle read receipt
        function handleReadReceipt(message) {
            const from = message.fromUser;
            const messageId = message.messageId;
            
            addSystemMessage(`${from} has read your message (ID: ${messageId})`);
        }
        
        // Send message
        function sendMessage(message) {
            if (!socket || socket.readyState !== WebSocket.OPEN) {
                addSystemMessage('Not connected to server');
                return;
            }
            
            socket.send(JSON.stringify(message));
        }
        
        // Send file data
        function sendFileData(fileId) {
            if (!pendingFileTransfer || !socket || socket.readyState !== WebSocket.OPEN) {
                addSystemMessage('Cannot send file data');
                return;
            }
            
            const file = pendingFileTransfer.file;
            const reader = new FileReader();
            
            reader.onload = function(event) {
                const arrayBuffer = event.target.result;
                socket.send(arrayBuffer);
                addSystemMessage(`File data sent (${formatFileSize(file.size)})`);
                pendingFileTransfer = null;
            };
            
            reader.onerror = function(error) {
                console.error('Error reading file:', error);
                addSystemMessage(`Error reading file: ${error.message}`);
                pendingFileTransfer = null;
            };
            
            reader.readAsArrayBuffer(file);
        }
        
        // Send read receipt
        function sendReadReceipt(toUser, messageId) {
            const message = {
                type: 'READ_RECEIPT',
                toUser: toUser,
                messageId: messageId
            };
            
            sendMessage(message);
        }
        
        // Add message to container
        function addMessage(type, content) {
            const messageElem = document.createElement('div');
            messageElem.className = `message ${type}`;
            messageElem.textContent = content;
            
            messageContainer.appendChild(messageElem);
            messageContainer.scrollTop = messageContainer.scrollHeight;
        }
        
        // Add system message
        function addSystemMessage(content) {
            addMessage('system', content);
        }
        
        // Update user list
        function updateUserList() {
            userList.innerHTML = '';
            
            const users = Object.keys(userStatusMap);
            
            if (users.length === 0) {
                const noUsersElem = document.createElement('p');
                noUsersElem.textContent = 'No users online';
                userList.appendChild(noUsersElem);
                return;
            }
            
            users.forEach(username => {
                if (username === currentUser) return;
                
                const userElem = document.createElement('div');
                userElem.className = 'user-item';
                userElem.textContent = `${username} (${userStatusMap[username] ? 'online' : 'offline'})`;
                
                userElem.addEventListener('click', () => {
                    document.getElementById('recipient').value = username;
                    document.getElementById('fileRecipient').value = username;
                    document.getElementById('friendUsername').value = username;
                    
                    const selectedUsers = document.querySelectorAll('.user-item.selected');
                    selectedUsers.forEach(user => user.classList.remove('selected'));
                    userElem.classList.add('selected');
                });
                
                userList.appendChild(userElem);
            });
        }
        
        // Set connection status
        function setConnectionStatus(isConnected) {
            if (isConnected) {
                connectionStatus.textContent = 'Connected';
                connectionStatus.className = 'status online';
                connectBtn.disabled = true;
                disconnectBtn.disabled = false;
                sendTextBtn.disabled = false;
                sendTypingBtn.disabled = false;
                sendFileBtn.disabled = false;
                sendFriendRequestBtn.disabled = false;
                acceptFriendBtn.disabled = false;
                rejectFriendBtn.disabled = false;
                postMomentBtn.disabled = false;
                likeBtn.disabled = false;
                commentBtn.disabled = false;
            } else {
                connectionStatus.textContent = 'Disconnected';
                connectionStatus.className = 'status offline';
                connectBtn.disabled = false;
                disconnectBtn.disabled = true;
                sendTextBtn.disabled = true;
                sendTypingBtn.disabled = true;
                sendFileBtn.disabled = true;
                sendFriendRequestBtn.disabled = true;
                acceptFriendBtn.disabled = true;
                rejectFriendBtn.disabled = true;
                postMomentBtn.disabled = true;
                likeBtn.disabled = true;
                commentBtn.disabled = true;
                
                // Clear user status
                userStatusMap = {};
                updateUserList();
            }
        }
        
        // Format file size
        function formatFileSize(bytes) {
            if (bytes < 1024) return bytes + ' B';
            else if (bytes < 1048576) return (bytes / 1024).toFixed(2) + ' KB';
            else if (bytes < 1073741824) return (bytes / 1048576).toFixed(2) + ' MB';
            else return (bytes / 1073741824).toFixed(2) + ' GB';
        }
    </script>
</body>
</html> 